import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authService, type User, type LoginData, type RegisterData } from '../services/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 初始化认证状态
  const initAuth = async () => {
    const savedToken = authService.getToken()
    if (savedToken) {
      token.value = savedToken
      try {
        await fetchProfile()
      } catch (error) {
        // token可能已过期，清除认证状态
        logout()
      }
    }
  }

  // 获取用户信息
  const fetchProfile = async () => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await authService.getProfile()
      if (response.success && response.data) {
        user.value = response.data.user
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取用户信息失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 用户登录
  const login = async (loginData: LoginData) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await authService.login(loginData)
      if (response.success && response.data) {
        token.value = response.data.token
        user.value = response.data.user
        return response
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '登录失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 用户注册
  const register = async (registerData: RegisterData) => {
    try {
      isLoading.value = true
      error.value = null
      
      const response = await authService.register(registerData)
      if (response.success && response.data) {
        token.value = response.data.token
        user.value = response.data.user
        return response
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '注册失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 用户登出
  const logout = () => {
    authService.logout()
    user.value = null
    token.value = null
    error.value = null
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 获取当前token
  const getToken = () => {
    return authService.getToken()
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    error,
    
    // 计算属性
    isAuthenticated,
    
    // 方法
    initAuth,
    fetchProfile,
    login,
    register,
    logout,
    clearError,
    getToken
  }
})